package com.bsoft.rpc.basic.transport;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {

    public void run(int port){
        // 创建一个负责接收客户端连接的线程组：BossGroup，指定线程数为1（默认8）
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 创建一个负责处理网络读写的线程组：WorderGroup，默认8
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 创建服务端启动类
        ServerBootstrap bootStrap = new ServerBootstrap();
        try {
            bootStrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 通过channel拿到pipeline，把处理类注册到管道中
                            socketChannel.pipeline()
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                    .addLast(new NettyServerHandler());
                        }
                    });

            // 绑定一个端口，启动服务
            ChannelFuture channelFuture = bootStrap.bind(port).sync();
            log.info("--- server is started for port:{} ---", port);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyServer nettyServer = new NettyServer();
        nettyServer.run(8888);
    }
}
